package com.sunyard.utils.msg;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 签名工具类
 *
 * @author zhix.huang
 * @date 2018.7.20
 */
public class SignatureUtil {

    private static Logger logger = Logger.getLogger(SignatureUtil.class);

    /**
     * @param bean
     * @return
     */
    public static String assmeblyPlainText(Object bean) {
        if (null == bean) {
            return "";
        }
        Map<String, String> map = new HashMap<String, String>();
        for (Method method : bean.getClass().getMethods()) {
            try {
                if (!method.getName().startsWith("get") || "getClass".equalsIgnoreCase(method.getName())) {
                    continue;
                }
                Object o = method.invoke(bean);
                if (o != null && StringUtils.isNotEmpty(o.toString()) && !"getSignature".equalsIgnoreCase(method.getName().toLowerCase())) {
                    String feildName = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4);
                    if (o instanceof Date) {
                        map.put(feildName, DateFormatUtil.dateTimeFormat((Date) o, DateFormatUtil.YYYYMMDDHHMMSS));// 所有日期类型的统一转换成yyyyMMddHHmmss
                    } else {
                        map.put(feildName, o.toString());
                    }
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return hex(map);
    }

    /**
     * 排序并组装签名明文串
     *
     * @param map
     * @return
     */
    public static String hex(Map<String, String> map) {
        String[] strs = new String[map.size()];
        map.keySet().toArray(strs);
        Arrays.sort(strs);
        StringBuffer source = new StringBuffer();
        for (String str : strs) {
            source.append(str + "=" + map.get(str) + "&");
        }
        String bigstr = source.substring(0, source.length() - 1);
        logger.debug("sign bigstr=" + bigstr);
        return bigstr;
    }

    /**
     * 验签
     *
     * @param signature
     * @param object
     * @return
     */
    public static boolean verify(String signature, Object object, String publicKey) {
        String plainText = assmeblyPlainText(object);
        return MyRSAUtils.verifySignature(publicKey, signature, plainText, MyRSAUtils.MD5_SIGN_ALGORITHM);
    }

    /**
     * 验签
     *
     * @param signature
     * @return
     */
    public static boolean verifyByPlainText(String signature, String plainText, String publicKey) {
        return MyRSAUtils.verifySignature(publicKey, signature, plainText, MyRSAUtils.MD5_SIGN_ALGORITHM);
    }

    /**
     * 应答签名
     *
     * @param respMap
     * @return
     */
//    public static String signResp(Map<String, String> respMap) {
//        return MyRSAUtils.sign(QrcodeConstant.PRIVATE_KEY, hex(respMap), MyRSAUtils.MD5_SIGN_ALGORITHM);
//    }

    /**
     * 应答签名
     *
     * @param respMap
     * @return
     */
    public static String signResp(String privateKey, Map<String, String> respMap) {
        return MyRSAUtils.sign(privateKey, hex(respMap), MyRSAUtils.MD5_SIGN_ALGORITHM);
    }

   /* public static void main(String[] args) {
        // String str =
        // "{\"orgId\":\"004495\",\"terminalId\":\"10101\",\"authCode\":\"134827594949617149\",\"subMerName\":\"鼎尚好数码店\",\"commodityName\":\"维达抽纸(箱)\",\"notifyUrl\":\"http://www.redonesoft.cn\",\"storeId\":\"001\",\"transAmt\":\"1\",\"signature\":\"BpX+4ZU0/Bh2Dwtb7xuUfuLPSyOmA2phaSSd11jeYozSi1/oRTuTb5unvc2KJm8vFPFLZD5xxY/C8lLWsZEU806Vbt1BHgY1+AlKTeDDUTSa2QNPc/IaY8aAVisU2fhLZIXQE7xHybS1t8ktYUQcoaIyK8ADK6V5wtZvWbpZZ0k\u003d\",\"merNo\":\"18493799\",\"productId\":\"0106\",\"version\":\"v1.0\"}";
        // PayUnifiedVo reqParams = JSON.parseObject(str, PayUnifiedVo.class);
        // boolean verify = verify(reqParams.getSignature(), reqParams,
        // "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC86/RgG0ppFTmSkl/BF6iAwyhNYXyzhad6qVDSle6i1ioWxkd4rwIK1U++GhL0VpphtxyyWGXsghI1iukjipJVwHRqV6BQ+zXflORdBqhf1Z6DW9LOPMpray+prV5Fk08fglcel2tv9rAaJKzXLz6L9osgXMDcka2/GYTyV93UwwIDAQAB");
        // System.out.println(verify);

        payReq();
    }*/

    /*public static void payReq() {
        Map<String, String> reqMap = new HashMap<String, String>();
        reqMap.put("version", "v1.0");
        reqMap.put("productId", "0106");
        reqMap.put("merNo", "11");
         reqMap.put("outOrderNo", "PD20171025006");
        reqMap.put("notifyUrl", "http://www.redonesoft.cn");
        reqMap.put("transAmt", "1");
        reqMap.put("commodityName", "维达抽纸箱");
        reqMap.put("authCode", "134954691066579");
        reqMap.put("storeId", "001");
        reqMap.put("terminalId", "10101");
        reqMap.put("subMerName", "鼎尚好数码店");
        reqMap.put("orgId", "029177");
        try {
            reqMap.put("signature",
                    signResp(
                            "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALNGsWB6ee+NppkBAfItKI9hS7g71bBjxpai0JVtGC3frww49T6byTN6yXEiu+YiHlF/GdO3x9Prfg/KhS6VBwvJyqprI8XkEWlB9JywAierG/X1Lvr1U0pTb84AzXvihkeEfWFZULRrWvK1k0/boX3aeKQpdO7CNXL8L8wqIfvfAgMBAAECgYACVKTxsCXtq1XDH3Q7BcNFOeqWFpEMnf9y7eLwTl7GGeZYrlTh33yaIrqDsgPnVgI25QQc8IK0ipc09VkN5foVc5L/DzbUZj8D8h78lpp3tVQlVbWc06/+9OBodm7XxZ6DEU5rQokFtpV5zokvaEyyaFwi21I/t6QAw63136CcoQJBAN8Up/HKgrW9uo2wjT8egnWu1cqlZYX+ksdP6PnnjxPsJnhXwqJVA+P8gpFjaLzn7gCbWlaPJ109T9Mr0xtiWGUCQQDNuzpMT8N1adwIt9QSOXxn8u+ImaXe27wXu7yC5nbiWQV1dy1zl9vqKqPRj3gZ4tBvVbYn5hFX1SlD1wloJITzAkBoBdnKhgQteytiptE2faOX/M70j+unb+5BwqGA5tlxEM1fkIzR5ZLK3RSFdzV/4Sa6YbbeZiKU9+IhNm5adqGBAkAUK0vO2W8HHsa0kBkZZEtfAYEcOjv5uj8ZcI1No/x5ulJ/rpxlHbkwnteKnu8eUo8uqw99n9+JZdtyzC0e6Z2jAkEAm1zPKfCkdc3n6yADqW9fySsohQuRbsq+/RaiulflLnfkhDEhlOKgAns/4AhY6sxkaiYzCOxkANwjGmSNxtWDRA==",
                            reqMap));
            Gson gson = new Gson();
            String content = gson.toJson(reqMap);
            HttpResponse doHttp = HttpClientHelper.doHttp("http://test.buybal.com/buybal-api/v1.0/pay/unified", "POST", "utf-8", content, "60000");
            System.out.println(doHttp);
        } catch (exception e) {
            e.printStackTrace();
        }
    }*/
}
